<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import CodeBlock from '@components/CodeBlock.vue'

const router = useRouter();
const message = ref('');
const notification = ref(null);

// 演示内置的全局属性（从main.js注入）
const showGlobalMessage = () => {
  // 访问全局方法
  if (window.app && window.app.config.globalProperties.$showMessage) {
    window.app.config.globalProperties.$showMessage('这是一个全局消息！');
  } else {
    alert('全局方法未正确挂载');
  }
};

// 演示自定义插件功能
const showNotification = (type) => {
  const types = {
    success: { text: '操作成功！', color: '#4CAF50' },
    error: { text: '操作失败！', color: '#F44336' },
    info: { text: '这是一条信息。', color: '#2196F3' },
    warning: { text: '警告信息！', color: '#FF9800' }
  };
  
  const notificationData = types[type];
  notification.value = {
    show: true,
    text: notificationData.text,
    color: notificationData.color,
    timestamp: Date.now()
  };
  
  // 3秒后自动隐藏
  setTimeout(() => {
    notification.value.show = false;
  }, 3000);
};

// 模拟插件创建过程
const pluginCreationCode = `// 创建一个简单的Vue插件
const MyPlugin = {
  install(app, options = {}) {
    // 1. 添加全局属性
    app.config.globalProperties.$myPlugin = {
      version: '1.0.0',
      options: options
    };
    
    // 2. 添加全局方法
    app.config.globalProperties.$myMethod = (param) => {
      console.log('MyPlugin method called with:', param);
      return 'Plugin result';
    };
    
    // 3. 提供依赖注入值
    app.provide('myPlugin', {
      version: '1.0.0',
      ...options
    });
    
    // 4. 添加全局组件
    // app.component('MyGlobalComponent', MyComponent);
    
    // 5. 添加全局指令
    // app.directive('my-directive', myDirective);
  }
};

// 使用插件
app.use(MyPlugin, { 
  debug: true,
  apiKey: 'demo-key'
});`;

// 模拟路由插件功能
const navigateToHome = () => {
  router.push('/');
};

// 表单处理示例（使用插件风格的验证）
const formData = ref({
  username: '',
  email: ''
});

const validateForm = () => {
  let isValid = true;
  const errors = [];
  
  if (!formData.value.username) {
    errors.push('用户名不能为空');
    isValid = false;
  }
  
  if (!formData.value.email) {
    errors.push('邮箱不能为空');
    isValid = false;
  } else {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.value.email)) {
      errors.push('邮箱格式不正确');
      isValid = false;
    }
  }
  
  if (isValid) {
    showNotification('success');
  } else {
    message.value = errors.join(', ');
    showNotification('error');
  }
};

// 导出状态供演示用
const isPluginActive = ref(true);

onMounted(() => {
  // 将应用实例保存到window以便在演示中访问
  if (!window.app) {
    // 在真实应用中，app实例应该通过provide/inject获取
    // 这里仅为演示目的
    console.log('应用实例未在window上挂载');
  }
});
</script>

<template>
  <div class="plugins-demo">
    <h2 class="demo-title">🔌 Vue 3 插件系统演示</h2>
    
    <p class="demo-description">
      Vue 3插件系统允许你全局扩展Vue应用功能，添加全局属性、方法、组件、指令等。
    </p>
    
    <div class="demo-grid">
      <!-- 全局属性演示 -->
      <div class="demo-card">
        <h3 class="card-title">全局属性与方法</h3>
        <div class="demo-content">
          <p>Vue插件可以向应用实例添加全局属性和方法，这些属性和方法在所有组件中都可以访问。</p>
          <button class="action-btn" @click="showGlobalMessage">
            调用全局消息方法
          </button>
          <div class="note">
            <p>注意：全局方法 $showMessage 在 main.js 中定义</p>
          </div>
        </div>
      </div>
      
      <!-- 通知插件演示 -->
      <div class="demo-card">
        <h3 class="card-title">通知插件示例</h3>
        <div class="demo-content">
          <div class="notification-buttons">
            <button class="action-btn success" @click="showNotification('success')">
              成功通知
            </button>
            <button class="action-btn error" @click="showNotification('error')">
              错误通知
            </button>
            <button class="action-btn info" @click="showNotification('info')">
              信息通知
            </button>
            <button class="action-btn warning" @click="showNotification('warning')">
              警告通知
            </button>
          </div>
        </div>
      </div>
      
      <!-- 插件创建演示 -->
      <div class="demo-card">
        <h3 class="card-title">创建自定义插件</h3>
        <div class="demo-content">
            
          <!-- <div class="code-snippet"> -->
            <!-- <pre>{{  }}</pre> -->
             <CodeBlock 
            :code="pluginCreationCode" 
            language="javascript" 
            :showLineNumbers="true" 
            :defaultDarkMode="false"
          />
          <!-- </div> -->
          <p class="code-explanation">
            插件通过install方法注册，可以添加全局属性、方法、组件、指令或提供依赖注入值。
          </p>
        </div>
      </div>
      
      <!-- 路由插件演示 -->
      <div class="demo-card">
        <h3 class="card-title">路由插件</h3>
        <div class="demo-content">
          <p>Vue Router 是一个官方插件，用于处理单页面应用的路由。</p>
          <button class="action-btn" @click="navigateToHome">
            导航到首页
          </button>
          <p class="current-route">
            当前路由: {{ router.currentRoute.value.path }}
          </p>
        </div>
      </div>
      
      <!-- 表单验证插件风格 -->
      <div class="demo-card">
        <h3 class="card-title">表单验证（插件风格）</h3>
        <div class="demo-content">
          <div class="form-group">
            <label>用户名:</label>
            <input 
              v-model="formData.username" 
              type="text" 
              class="form-input"
              placeholder="请输入用户名"
            />
          </div>
          <div class="form-group">
            <label>邮箱:</label>
            <input 
              v-model="formData.email" 
              type="email" 
              class="form-input"
              placeholder="请输入邮箱"
            />
          </div>
          <button class="action-btn" @click="validateForm">
            验证表单
          </button>
          <p v-if="message" class="error-message">{{ message }}</p>
        </div>
      </div>
      
      <!-- 插件最佳实践 -->
      <div class="demo-card">
        <h3 class="card-title">插件最佳实践</h3>
        <div class="demo-content">
          <ul class="best-practices-list">
            <li><strong>模块化设计:</strong> 插件应具有清晰的功能边界</li>
            <li><strong>配置选项:</strong> 提供合理的默认配置和自定义选项</li>
            <li><strong>类型安全:</strong> 为插件提供TypeScript类型定义</li>
            <li><strong>避免全局污染:</strong> 谨慎使用全局属性</li>
            <li><strong>按需加载:</strong> 支持Tree-Shaking</li>
            <li><strong>文档完善:</strong> 提供清晰的使用文档</li>
          </ul>
        </div>
      </div>
    </div>
    
    <!-- 通知组件 -->
    <transition name="notification">
      <div 
        v-if="notification && notification.show" 
        class="notification" 
        :style="{ backgroundColor: notification.color }"
      >
        {{ notification.text }}
      </div>
    </transition>
  </div>
</template>

<style scoped>
.plugins-demo {
  padding: 20px;
  position: relative;
}

.demo-title {
  text-align: center;
  margin-bottom: 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.demo-description {
  text-align: center;
  margin-bottom: 30px;
  color: #666;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.demo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.demo-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.card-title {
  color: #667eea;
  margin-bottom: 15px;
}

.demo-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 按钮样式 */
.action-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  background-color: #667eea;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
}

.action-btn:hover {
  opacity: 0.9;
}

.action-btn.success {
  background-color: #4CAF50;
}

.action-btn.error {
  background-color: #F44336;
}

.action-btn.info {
  background-color: #2196F3;
}

.action-btn.warning {
  background-color: #FF9800;
}

/* 通知按钮组 */
.notification-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 提示框 */
.note {
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 6px;
  font-size: 0.9rem;
  color: #666;
}

/* 代码片段 */
.code-snippet {
  background-color: #f5f5f5;
  border-radius: 6px;
  padding: 15px;
  overflow-x: auto;
  max-height: 300px;
}

.code-snippet pre {
  margin: 0;
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.8rem;
  color: #333;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.code-explanation {
  font-size: 0.9rem;
  color: #666;
  font-style: italic;
}

/* 表单样式 */
.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.error-message {
  color: #F44336;
  font-size: 0.9rem;
  margin-top: 5px;
}

/* 路由信息 */
.current-route {
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 6px;
  font-family: monospace;
  font-size: 0.9rem;
}

/* 最佳实践列表 */
.best-practices-list {
  padding-left: 20px;
}

.best-practices-list li {
  margin-bottom: 8px;
  color: #555;
}

/* 通知组件 */
.notification {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  color: white;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  z-index: 1000;
  min-width: 200px;
  text-align: center;
}

/* 通知动画 */
.notification-enter-active, .notification-leave-active {
  transition: all 0.3s ease;
}

.notification-enter-from, .notification-leave-to {
  opacity: 0;
  transform: translateX(100%);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .demo-grid {
    grid-template-columns: 1fr;
  }
  
  .notification {
    position: fixed;
    top: 10px;
    right: 10px;
    left: 10px;
    min-width: auto;
  }
}
</style>